var bubbledowndone = 0; //Variable utilisé pour vérifié sir les div de dialogue sont en display none ou non
var bubbletopdone = 0;
var type="";
var writedelay= 5;//tps en ms entre chaque lettre  40ms
var NbButton=0;
var NbPoint=0;
var AddButton=false;
var PlayVideo = false;
var DisplayPopUp = false;
var VideoName = "";
var NextScene = "";
var TypeEvent = "";
var PathJson  = "";
/*   VARIABLE FALSE TANT QUE PAS UTILISE */
var MapDialogue = false;
var MapDialogueCount = false;
///////////////////////////////////////////


	// this function will be called only once when the scene manager show this scene first time
	// initialize the scene controls and styles, and initialize your variables here
	// scene HTML and CSS will be loaded before this function is called
	//alert("compteur "+compteur+"    ");

	$.fn.teletype = function(opts){

			var $this = this,
			defaults = {
				animDelay: writedelay
			},settings = $.extend(defaults, opts);
		
		$.each(settings.text.split(''), function(i, letter){
			setTimeout(function(){
				$this.html($this.html() + letter);	
			}, settings.animDelay * i);
			 nbletter = i;
	});
		setTimeout(function(){
	 	_count = 1; //Fonction done
		compteur++; // On accremente le compteur utilise pour savoir quelle ligne de texte chercher
		}, settings.animDelay * nbletter);	

/*		var $this = this,
		defaults = {
			animDelay: writedelay
		},settings = $.extend(defaults, opts);
	
		alert(' text : '+settings.text);
		$this.html($this.html()+settings.text);
	
	

	 	_count = 1; //Fonction done
		compteur++; // On accremente le compteur utilise pour savoir quelle ligne de texte chercher
		*/
};

function CreateButton(nom,value,redirection,point,redirectionScene,IdClass){	
	alert("CreateButton "+nom+"  value "+value+' IdClass '+IdClass+'');
	
	//CSS pour le premier boutton
	alert('Nb Button '+NbButton);
	if(NbButton == 0){
		alert('IN DE NANANARD');
		$(''+IdClass+'').append("<div class='"+nom+" choix-button selected' value='"+redirection+";"+point+";"+redirectionScene+"'   ></div>"); 
	}else {
		$(''+IdClass+'').append("<div class='"+nom+" choix-button' value='"+redirection+";"+point+";"+redirectionScene+"'  ></div>"); 
	}

	$('.'+nom+'' ).sfButton({
		text:''+value+''
	});
	
	NbButton++;
}
////////////////////////////////////////////////////
//ASPECT BOUTON
function FocusCssButton (PosDialButton,mvt){
	alert('PostDialButton ' + PosDialButton);
	$('.Choice'+PosDialButton+'' ).removeClass("selected");
	PosDialButton = PosDialButton + mvt;
	if(PosDialButton == -1) PosDialButton=NbButton-1; else if(PosDialButton == NbButton ){
		PosDialButton = 0;
	};
	$('.Choice'+PosDialButton+'' ).addClass("selected");
	alert('-*-*-*-*-**--*-*-*-*-*    NbButton -> ' + NbButton);
}
/*///////////////////////////MAP/////////////////////////////*/
function ShowMap(IdMap){
	
	sf.scene.hide('CurrentScene');

	switch (IdMap){
	
	case "2":
		sf.scene.show('MapQueensPark');
		sf.scene.focus('MapQueensPark');
		break;	
	}
}

/*///////////////////////////POPUP/////////////////////////////*/
function ShowPopUp(Point){
	DisplayPopUp = true;
	$('.popup-hud .level').html('Level 2');
	$('.popup-hud .text-popup').html("Did you know the diference between Sawatdie krap and sawatdie kha ? Krap means you’re a boy, so yes , kha means you’re girl. Sorry not told you that before. If you dated a girl who said krap last time, I think she wasn't talking about me...");
	$('.popup-hud').fadeIn();
}
function HidePopUp(){
	$('.popup-hud .level').html('');
	$('.popup-hud .text-popup').html("");
	$('.popup-hud').fadeOut();
	DisplayPopUp = false;
}
///////////////////////////////////////////////////////////////*/

function ShowPoint(Point){
	NbPointTemp= parseInt(NbPoint)+parseInt(Point);

	$('.DisplayPoint span.point-add, .DisplayPoint span.point-total').html(''+NbPoint+'');
	$('.DisplayPoint span.point-add').html('+'+Point);
	$('.DisplayPoint span.point-total').html('+'+NbPoint);
    $(".picto-hud").css("visibility","visible").hide().fadeIn('slow',function() {
    	NbPoint= parseInt(NbPoint)+parseInt(Point);
    });

	/* Hide Button 
    setTimeout(function(){
	    $(".picto-hud").css("visibility","hidden");
		alert("NbPoint : "+NbPoint+"");
		},3000 );
	*/
    setTimeout(function(){
    	$('.DisplayPoint span.point-total').html(''+NbPoint+'');
    	$('.DisplayPoint span.point-add').html('');
		},3000 );
    
	if( NbPointTemp>5 ){
		alert("==========ShowPopUp ================ NbPoint "+NbPoint);
		ShowPopUp(NbPoint);
	}
	alert("---------------------------");
}

function AddPoint(Point){
	Score= true;
	ShowPoint(Point);
}
//////////////////////////////////////////////////
function ChangeCharacterImage(id){
	if(id != 1){
		$('div.image-character img').attr('src', 'images/character/'+id+'.png');
		$('div.image-character img').attr('class', 'character-image-'+id+'.png');
		$('div.image-character img').css("visibility","visible").fadeIn();
		// Animation Jquery, Slip effect 
		
		  $( "div.image-character" ).animate({
			    left: "50px"
			  }, 1500, function() {
				  	alert('Animation done');
			  });
	}
}

////////////////////////////////////////////////////
///////////////// Hiding functions /////////////////
function HideCharacterImage(){
	alert('function HideCharacterImage()'); 
	$('div.image-character img').css("visibility","hidden").fadeOut();
	$('div.image-character').css("left","-500px");

}

function HideBubbleTop(){
	$(".bubble-top").css("visibility","hidden").fadeOut();
}

function HideBubbleDown(){
	$(".bubble-down").css("visibility","hidden").fadeOut();
}

function HideButtons(){
	$('div.container .sf-ui-button').css("visibility","hidden").fadeOut();
}
function HideSelectIcon(){
// On peut afficher a nouveau des icons
SelectIcon = false;
$('.IconMap').css("visibility","visible").hide().fadeOut();
}

function HideAllDisplay(){
	HideCharacterImage();
	HideBubbleTop();
	HideBubbleDown();
	HideButtons();
	HideSelectIcon();
}
////////////////////////////////////////////////////

function parsingjson(){
	alert('Current Scene '+CurrentScene+'');

	alert("in parsingjson "+_count+"  scene "+scene);
	
	PathJson = 'app/dialogue/'+lang+'/'+scene;
	
	  $.getJSON(PathJson, function(data) {
		  		alert(PathJson);


				var output="";
				i = compteur;
				var key=0;
				var count = 0;
				for(key in data.line) {
				  if(data.line.hasOwnProperty(key)) {
				    count++;
				  }
				}
				//On lance la fonction apres vérification que la variable compteur
				//ne soit pas superieur  au nb de ligne disponible dans le json
				alert("Compteur ligne "+count);
				alert("if(count> i)"+' if( '+count+' > '+i+' )');
			if(count> i){
					
				var IdClass = "";

				type= data.line[i].type;

				if(data.line[i].id == 1){
					IdClass = ".container"; 
					if(bubbledowndone == 0){
												$(".bubble-down").css("visibility","visible").hide().fadeIn('slow',function() {
												bubbledowndone=1;});
											}
					}else{
						IdClass = ".container-pnj";	

						if(bubbletopdone == 0){
							$(".bubble-top").css("visibility","visible").hide().fadeIn('slow',function() {
					    	bubbletopdone=1;
							});
						}
					}
				//Efface la bulle pour un nouveau contenu
				$(''+IdClass+'').html('');


				/*/Si MapDialogue on compte le nombre de ligne
				if (MapDialogue  != false){
					var MapDialogueCount = 0;
					for(key in data.line) {
					if(data.line[i].dialogue.hasOwnProperty(key)) {
					  	MapDialogueCount++;
				  	}
					}
				}*/
				alert(' MapDialogueCount: '+MapDialogueCount);

				switch (type){
				
					case "text":
						alert(' TEXT ');	
						output+=data.line[i].content;
						ChangeCharacterImage(data.line[i].id);
						 $(''+IdClass+'').html('<span class="name-character-bubbles">'+data.line[i].auteur+'</span> : ');
					     $(''+IdClass+'').teletype({
					    	 						animDelay: writedelay,
					    	 						text: ''+output+''},1); 
						break;
						
					case "question":
						alert(' QUESTION ');	
						output+= data.line[i].content;
						
						ChangeCharacterImage(data.line[i].id);
	
						 $(''+IdClass+'').html('<span class="name-character-bubbles">'+data.line[i].auteur+'</span> : ');
	
					     $(''+IdClass+'').teletype({
													animDelay: writedelay,
													text: ''+output+''},1);  
	 
					     AddButton=true;
								setTimeout(function(){
								//alert('#dataaaaaaaaaaa hh '+data.line[i].choice.length+'  '+output.length);	
									for (var x=0; x < data.line[i].choice.length ; x++) {	
										//CREATION DE BOUTON APRES AFFICHAGE TEXT 
										//alert('#choix'+x+'  '+data.line[i].choice[x].answer);
										CreateButton('Choice'+x,data.line[i].choice[x].answer,data.line[i].choice[x].redirection,data.line[i].choice[x].point,data.line[i].choice[x].redirectionScene,IdClass);
									}
						
								}, writedelay * output.length  );			
						break;
						
					case "interlude":
						alert(' INTERLUDE ');	
						PlayVideo = true; // Play video
						output+=data.line[i].content;
						ChangeCharacterImage(data.line[i].id);
						 
						$(''+IdClass+'').html('<span class="name-character-bubbles">'+data.line[i].auteur+'</span> : ');
						 
					    $(''+IdClass+'').teletype({
					    							animDelay: writedelay,
					    							text: ''+output+''},1);
					    
						NextScene = data.line[i].nextscene;
						VideoName = data.line[i].video;
						
						//Si dialogue contient du texte
						if(data.line[i].dialogue != ""){
							MapDialogue = data.line[i].dialogue;
							alert('MapDialogue switch '+MapDialogue);
						}else{
							alert("kikoooooooooooooooooooooooooooooooooooo");
							MapDialogue = false;
						}
						
						setTimeout(function(){
						// On lance la page vidéo
							sf.scene.hide(CurrentScene);
							sf.scene.show('Player');
							sf.scene.focus('Player');
						}, (writedelay * output.length)+2000  );	
	
						break;
					case "interludeYoutube":
						alert(' INTERLUDEYOUTUBE ');	
						PlayVideo = true; // Play Video
						output+=data.line[i].content;
						ChangeCharacterImage(data.line[i].id);
						 
						$(''+IdClass+'').html('<span class="name-character-bubbles">'+data.line[i].auteur+'</span> : ');
						 
					    $(''+IdClass+'').teletype({
						animDelay: writedelay,
						text: ''+output+''
					     },1);
					    
						NextScene = data.line[i].nextscene;
						VideoName = data.line[i].video;
						alert(' Youtube video url= '+VideoName);
						//Si dialogue contient du texte
						if(data.line[i].dialogue != ""){
									MapDialogue = data.line[i].dialogue;
							}else{
									MapDialogue = false;
								}	
						
						setTimeout(function(){
						// On lance la page vidéoYoutube aprés plusieurs seconde
							sf.scene.hide(CurrentScene);
							sf.scene.show('PlayerYoutube');
							sf.scene.focus('PlayerYoutube');
						}, (writedelay * output.length)+2000  );	
	
						break;		
					case "map":
						alert('MAP');	
						ShowMap(data.line[i].idmap);
						break;
						
					case "event":
						alert(' EVENT ');
						output+=data.line[i].content;
						ChangeCharacterImage(data.line[i].id);
						 $(''+IdClass+'').html('<span class="name-character-bubbles">'+data.line[i].auteur+'</span> : ');
					     $(''+IdClass+'').teletype({
					    	 								animDelay: writedelay,
															text: ''+output+''},1);

					    TypeEvent = data.line[i].eventtype;
					    alert("-------------------- "+data.line[i].eventtype+"--------------------");
					    alert("____________________ "+TypeEvent+"_____________________");
					    //HideCharacterImage();
					    //HideBubbleTop();
					    //HideBubbleDown();
						break;
				}		
		}else{
								alert(' FIN COMPTEUR POUR MAP   ');
									$(".bubble-top").css("visibility","visible").hide().fadeOut('slow',function() {
										bubbletopdone=0;
									});
									
									$(".bubble-down").css("visibility","visible").hide().fadeOut('slow',function() {
										bubbledowndone=0;
									});
									_count = 1; //Fonction done
									MapDialogue = false;
									// On peut afficher a nouveau des icons
									SelectIcon = true;
									$('.IconMap').css("visibility","visible").hide().fadeIn('slow',function() {});
								}
				
	  });  
}

//Verifie que la fonction appel une seule fois une fonction 
function OneTime() {
	alert("function OneTime() "+_count);
	alert("OneTime compteur "+compteur+"    ");

		if ( _count < 2 ){
		//replace the line below with the code that you only want to run once
			_count = _count + 1 ;
			parsingjson();
		}
}
